//
//  PublishVC.swift
//  SinaWeiBo
//
//  Created by ZKJ on 2017/9/21.
//  Copyright © 2017年 ZKJ. All rights reserved.
//

import UIKit
import SVProgressHUD

class PublishVC: UIViewController {
    // MARK:- 属性
    fileprivate lazy var titleView : PublishTitleView = PublishTitleView()
    fileprivate lazy var imageArr : [UIImage] = [UIImage]()
    fileprivate lazy var emoticonVC : EmoticonController = EmoticonController { (emoticon) in
        self.zkjTextView.insertEmoticon(emoticon: emoticon)
        self.textViewDidChange(self.zkjTextView)
    }

    // MARK:- 控件
    @IBOutlet weak var zkjTextView: ZkjTextView!
    @IBOutlet weak var picSelCLView: PicSelCollectionView!
    
    // MARK:- 控件的约束属性
    @IBOutlet weak var toolBarBottomConstant: NSLayoutConstraint!
    @IBOutlet weak var picSelColViewHeight: NSLayoutConstraint!
    
    // MARK:- 系统回调函数
    override func viewDidLoad() {
        super.viewDidLoad()
        setUpNavigationBar()
        setUpNotification()
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        if picSelColViewHeight.constant == 0 {
            zkjTextView.becomeFirstResponder()
        }
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
}

// MARK:- 布局UI界面
extension PublishVC {
    // MARK:- 布局导航条
    fileprivate func setUpNavigationBar() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: .plain, target: self, action: #selector(PublishVC.cancleClick))
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发布", style: .plain, target: self, action: #selector(PublishVC.publishClick))
        navigationItem.rightBarButtonItem?.isEnabled = zkjTextView.hasText
        titleView.frame = CGRect(x: 0, y: 0, width: 150, height: 40)
        navigationItem.titleView = titleView
    }
    
    // MARK:- 布局输入框
    fileprivate func setUpInputView() {
        
    }
    
    fileprivate func setUpNotification() {
        //监听键盘
        NotificationCenter.default.addObserver(self, selector: #selector(PublishVC.keyboardWillChangeFrame(note:)), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
        
        //监听图片选择
        NotificationCenter.default.addObserver(self, selector: #selector(PublishVC.picSelectClick), name: NSNotification.Name(rawValue: PicPickerAddPhotoNote), object: nil)
        
        //监听删除照片
        NotificationCenter.default.addObserver(self, selector: #selector(PublishVC.picDeleteClick(note:)), name: Notification.Name(PicPickerDeletePhotoNote), object: nil)
    }
}

// MARK:- 监听点击事件
extension PublishVC {
    @objc fileprivate func cancleClick() {
        print("取消")
        zkjTextView.resignFirstResponder()
        dismiss(animated: true, completion: nil)
    }
    
    @objc fileprivate func publishClick() {
//        print("发布")
//        print(zkjTextView.getEmoticon())
        //1.退出键盘
        zkjTextView.resignFirstResponder()
        
        //2.定义回调的闭包
        let finishCallBack = { (isSuccess : Bool) in
            if !isSuccess {
                SVProgressHUD.showError(withStatus: "发送失败！")
                self.dismiss(animated: true, completion: nil)
                return
            }
            SVProgressHUD.showSuccess(withStatus: "发送成功")
            self.dismiss(animated: true, completion: nil)
        }
        
        if let image = imageArr.first {
            ZkjNetworkTool.shareInstance.sendWordAndPictureStatus(status: zkjTextView.getEmoticon(), image: image, isSuccess: finishCallBack)
        } else {
            ZkjNetworkTool.shareInstance.sendWordStatus(status: zkjTextView.getEmoticon(), isSuccess: finishCallBack)
        }
    }
    
    @objc fileprivate func keyboardWillChangeFrame(note : NSNotification) {
//        print(note.userInfo ?? "")
        let duration = note.userInfo?[UIKeyboardAnimationDurationUserInfoKey] as! TimeInterval
        let rect = (note.userInfo?[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
        toolBarBottomConstant.constant = UIScreen.main.bounds.height - rect.origin.y
        UIView.animate(withDuration: duration) { 
            self.view.layoutIfNeeded()
        }
    }
    
    //选择图片
    @IBAction func picSelClick() {
        zkjTextView.resignFirstResponder()
        picSelColViewHeight.constant = UIScreen.main.bounds.height * 0.65 + 20
        UIView.animate(withDuration: 0.25) { 
            self.view.layoutIfNeeded()
        }
    }
    
    //切换表情键盘
    @IBAction func emoticonClick() {
        //1.退出键盘
        zkjTextView.resignFirstResponder()
        
        //2.切换键盘
        zkjTextView.inputView = zkjTextView.inputView != nil ? nil : emoticonVC.view
        
        //3.弹出键盘
        zkjTextView.becomeFirstResponder()
    }
    
    //切换默认键盘
    @IBAction func defaultKeyboardBtnClick() {
        zkjTextView.resignFirstResponder()
        zkjTextView.inputView = nil
        zkjTextView.becomeFirstResponder()
    }
}

// MARK:- 添加照片和删除照片的事件
extension PublishVC {
    //添加照片
    @objc fileprivate func picSelectClick() {
        
        if imageArr.count > 9 {
            let alertVC = UIAlertController(title: "温馨提示", message: "照片不能超过9张", preferredStyle: .alert)
            let action1 = UIAlertAction(title: "确定", style: .default, handler: { (_) in
                return
            })
            alertVC.addAction(action1)
            present(alertVC, animated: true, completion: nil)
            return
        }
        
        // 1.判断数据源是否可用
        if !UIImagePickerController.isSourceTypeAvailable(.photoLibrary) {
            return
        }
        
        // 2.创建照片选择控制器
        let ipc = UIImagePickerController()
        
        // 3.设置来源
        ipc.sourceType = .photoLibrary
        
        // 4.设置代理
        ipc.delegate = self
        
        // 5.弹出选择照片的控制器
        present(ipc, animated: true, completion: nil)
    }
    
    //删除照片
    @objc fileprivate func picDeleteClick(note : Notification) {
        guard let image = note.object as? UIImage else {
            return
        }
        
        guard let index = imageArr.index(of: image) else {
            return
        }
        
        imageArr.remove(at: index)
        picSelCLView.imageArr = imageArr
    }
}

// MARK:- UIImagePicker的代理
extension PublishVC : UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
//        print(info)
        // 1.获取选中的照片
        let image = info[UIImagePickerControllerOriginalImage] as! UIImage
        
        // 2.添加到数组
        imageArr.append(image)
        picSelCLView.imageArr = imageArr
        dismiss(animated: true, completion: nil)
    }
}

// MARK:- textview代理
extension PublishVC : UITextViewDelegate {
    func textViewDidChange(_ textView: UITextView) {
        zkjTextView.placeHolderLabel.isHidden = textView.hasText
        navigationItem.rightBarButtonItem?.isEnabled = textView.hasText
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        zkjTextView.resignFirstResponder()
    }
}



